import java.io.*;
import java.lang.reflect.*;

import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

public class GenerateurStub {
	
	
	public static boolean ecrireFichier(Object o) {
		try {
		String nomClasse = o.getClass().getSimpleName();
		File ficStub = new File(nomClasse+"_stub.java");
		System.out.println("On va generer : "+ nomClasse+"_stub.java");
		FileWriter fw = new FileWriter(ficStub);
		Method[] methodes = o.getClass().getDeclaredMethods();
			fw.write("public class "+ nomClasse + "_stub extends SharedObject implements "+nomClasse+"_itf,java.io.Serializable {");
			
			fw.write("public " +nomClasse+ "_stub (int id, Object obj) {");
			fw.write("super(id, obj);");
			fw.write("}");
			
			for (int i = 0; i < methodes.length; i++) {
				Method meth = methodes[i];
				Class[] params = meth.getParameterTypes(); 
	            
				fw.write("public "+meth.getReturnType().getSimpleName()+" "+meth.getName()+"(");
				for (int j = 0; j < params.length; j++) {
					fw.write(params[j].getSimpleName()+" p"+j);
					if (j != params.length-1) {
						fw.write(", ");
					}
				}
				fw.write(") { ");
				fw.write(nomClasse+" x = ("+nomClasse+")obj;");
				if (meth.getReturnType().getSimpleName() != "void") {
					fw.write("return ");
				} 
				fw.write("x."+meth.getName()+"(");
				if (params.length != 0) {
					for (int j = 0; j < params.length; j++) {
						fw.write("p"+j);
						if (j != params.length-1) {
							fw.write(", ");
						}
					}
				}
				fw.write(");");
				fw.write("}");
				
			}
			fw.write("}");
			fw.close();
			Process p = Runtime.getRuntime().exec("javac " +nomClasse+"_stub.java");
			p.waitFor();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public static SharedObject instance (int id, Object o) {
		String nomStub = o.getClass().getSimpleName()+"_stub";
		Class stubClass;
		try {
			stubClass = Class.forName(nomStub);
			Constructor[] cons = stubClass.getConstructors();
			return (SharedObject) cons[0].newInstance(id, o);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/*
	public static void main (String[] args) {
		Object s = new Sentence();
		Boolean b = GenerateurStub.ecrireFichier(s);
	}*/
}
